/**
 * 配置
 * */
package org.zmhhxl.sample3.oauth2.a.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.zmhhxl.api.auth.RemoteThirdPartyService;
import org.zmhhxl.api.auth.RemoteUserInfoService;
import org.zmhhxl.api.auth.domain.entity.ThirdPartyUser;
import org.zmhhxl.common.core.utils.GeneralFunction;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

@Slf4j
public final class OAuth2UserRepositoryHandler implements Consumer<OAuth2User> {

   public final UserRepository userRepository = new UserRepository();

//   @Autowired
    private final RemoteThirdPartyService thirdPartyUserService;
//
//   @Autowired
    private final RemoteUserInfoService userInfoService;

  // @Autowired
   public OAuth2UserRepositoryHandler(RemoteUserInfoService userInfoService, RemoteThirdPartyService thirdPartyUserService) {
      this.thirdPartyUserService = thirdPartyUserService;
      this.userInfoService = userInfoService;
   }

   @Override
   public void accept(OAuth2User user) {
      //log.info("UserRepository =============");
      log.info("第三方登录成功2 CustomOAuth2User sssss =======  {} ", user.getAttributes());
      String domainUrl = GeneralFunction.extractDomain((String) GeneralFunction.mapFuzzyMatch(user.getAttributes(), "url",0.8).entrySet().stream().findFirst().orElse(null).getValue());

      // 获取第三方登录的id
      String sub = user.getName();

      if ((domainUrl != null) && (sub != null)){
         Optional<ThirdPartyUser> thirdPartyUser = thirdPartyUserService.findByThirdPartyIdAndThirdPartyDomain(sub, domainUrl).getData();//.getUserInfos().stream().map(UserInfo::getId).findFirst().orElseThrow();
         // 第一次登陆，保存用户信息
         if (thirdPartyUser.isEmpty()) {
            log.info("第三方登录成功5,第一次登陆准备保存 OAuth2User sssss {}", thirdPartyUser.get());
            ThirdPartyUser thirdPartyUser1 = new ThirdPartyUser();
            thirdPartyUser1.setThirdPartyId(sub);
            thirdPartyUser1.setThirdPartyDomain(domainUrl);
            thirdPartyUser1.setThirdPartyProtocol(GeneralFunction.extractUrlProtocol((String) user.getAttributes().get("url")));
            thirdPartyUser1.setThirdPartyType(user.getAttribute("type"));

            //thirdPartyUserService.save(thirdPartyUser1);
         }
      }

      // Capture user in a local data store on first authentication
//      if (this.userRepository.findByName(user.getName()) == null) {
//         //System.out.println("存储第一次用户: name sssss =======" + user.getName() + ", claims=" + user.getAttributes() + ", authorities=" + user.getAuthorities());
//         log.info("存储第一次用户: name sssss =======" + user.getName() + ", claims=" + user.getAttributes() + ", authorities=" + user.getAuthorities());
//         log.info("第三方信息保存,name sssss ====== thirdPartyId = {}, thirdPartyType URL = {}", user.getName(), user.getAttribute("url")); //sub
//         this.userRepository.save(user);
//
//      }
   }

   public static class UserRepository {

      private final Map<String, OAuth2User> userCache = new ConcurrentHashMap<>();

      public OAuth2User findByName(String name) {
         return this.userCache.get(name);
      }

      public void save(OAuth2User oauth2User) {
         this.userCache.put(oauth2User.getName(), oauth2User);
      }

   }

}
